package demo3;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        DBManager dbManager = new DBManager();
        Scanner scanner = new Scanner(System.in, "UTF-8");
        System.out.println("===== 简易数据库（优化版）=====");
        System.out.println("支持命令：CREATE TABLE / INSERT INTO / DELETE FROM / UPDATE / SELECT * / DROP TABLE");
        System.out.println("输入 'exit' 退出，输入 'help' 查看帮助");

        while (true) {
            System.out.print("\n请输入SQL语句: ");
            String sql = scanner.nextLine().trim();

            if ("exit".equalsIgnoreCase(sql)) {
                dbManager.writeDataDictionary();
                System.out.println("程序已退出，数据已保存");
                scanner.close();
                break;
            }

            if ("help".equalsIgnoreCase(sql)) {
                printHelp();
                continue;
            }

            if (sql.isEmpty()) continue;

            try {
                if (sql.toLowerCase().startsWith("create table")) {
                    dbManager.createTable(sql);
                } else if (sql.toLowerCase().startsWith("insert into")) {
                    dbManager.insertInto(sql);
                } else if (sql.toLowerCase().startsWith("delete from")) {
                    dbManager.deleteFrom(sql);
                } else if (sql.toLowerCase().startsWith("update")) {
                    dbManager.update(sql);
                } else if (sql.toLowerCase().startsWith("select * from")) {
                    dbManager.select(sql);
                } else if (sql.toLowerCase().startsWith("drop table")) {
                    dbManager.dropTable(sql);
                } else {
                    System.err.println("不支持的命令，请输入 'help' 查看格式");
                }

                dbManager.writeDataDictionary();
                dbManager.clearMemory();
            } catch (Exception e) {
                System.err.println("执行错误：" + e.getMessage());
            }
        }
    }

    private static void printHelp() {
        System.out.println("\n===== 命令示例 =====");
        System.out.println("1. 创建表：CREATE TABLE student(sid INT, name VARCHAR(20), PRIMARY KEY(sid));");
        System.out.println("2. 插入数据：INSERT INTO student(sid,name) VALUES(1,'张三');");
        System.out.println("3. 插入数据（简写）：INSERT INTO student VALUES(2,'李四',20,'男');");
        System.out.println("4. 查询数据：SELECT * FROM student;");
        System.out.println("5. 条件查询：SELECT * FROM student WHERE age>18;");
        System.out.println("6. 更新数据：UPDATE student SET age=19 WHERE sid=1;");
        System.out.println("7. 删除数据：DELETE FROM student WHERE sid=2;");
        System.out.println("8. 删除表：DROP TABLE student;");
        System.out.println("====================");
    }
}